package com.example.demo.netty.chat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

//网络客户端
public class NettyClient {
    public static void main(String[] args) throws  Exception{

        //1. 创建一个线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            //2. 创建客户端的启动对象，完成相关配置
            Bootstrap b = new Bootstrap();
            b
                    //3. 设置线程组
                    .group(group)
                    //4. 设置客户端通道的实现类（便于 Netty 做反射处理）
                    .channel(NioSocketChannel.class)
                    //5. 创建一个通道初始化对象
                    .handler(new ChannelInitializer<SocketChannel>() {
                         @Override
                         protected void initChannel(SocketChannel socketChannel) throws Exception {
                             //6.往Pipeline链中添加自定义的handler
                             socketChannel.pipeline().addLast(new NettyClientHandler());
                         }
                     });

            System.out.println("......Client is  ready......");

            //7.启动客户端去连接服务器端  connect方法是异步的   sync方法是同步阻塞的
            final ChannelFuture cf = b.connect("127.0.0.1",6668).sync();

            cf.addListener(new ChannelFutureListener() {
                /**
                 * 回调方法，上面的 b.connect()操作执行完之后触发
                 */
                public void operationComplete(ChannelFuture future)
                        throws Exception {
                    if (cf.isSuccess()) {
                        System.out.println("客户端连接成功!");
                    } else {
                        System.out.println("客户端连接失败!");
                    }
                }
            });

            //8.对通道关闭进行监听(异步非阻塞)
            cf.channel().closeFuture().sync();

        } finally {
            System.out.println("......关闭连接(异步非阻塞)......");
            group.shutdownGracefully();
        }

    }
}
